<template>
  <div class="view-fill">
    <div class="app-container-flex">
      <full-screen
        v-model="showDialog"
        :title="title"
        :btn-list="fullInfo.btnList"
        @returnBack="$emit('returnModify')"
      >
        <div class="model-panel">
          <div class="model-panel-title">
            <p>{{ $t('basic_information') }}</p>
          </div>
          <div class="model-panel-body">
            <page-form
              class="paddingBox order-model-formBox flex_wrap_start_start"
              v-model:ref-obj="formInfo.ref"
              :data="formInfo.data"
              :field-list="formInfo.fieldList"
              :label-width="formInfo.labelWidth"
              :rules="formInfo.rules"
            >
              <template v-slot:form-tsSystemCode>
                <select-model
                  v-model="formInfo.data.tsSystemCode"
                  type-code="client_id"
                  :clearable="false"
                  @change="changeCode"
                />
              </template>
            </page-form>
          </div>
        </div>
        <div class="model-panel">
          <div class="model-panel-title">
            <Tooltip :text="$t('detailInfo')" />
          </div>
          <div class="model-panel-body">
            <page-filter :filter-list="filterInfo.list">
              <template v-slot:filter-add>
                <el-button @click="add" :disabled="!formInfo.data.tsSystemCode"
                  >添加产品</el-button
                >
              </template>
              <template v-slot:filter-remove>
                <el-button :disabled="!canRemove" @click="remove"
                  >删除产品</el-button
                >
              </template>
              <template v-slot:filter-comparisonRule>
                <select-model
                  v-model="filterInfo.query.comparisonRule"
                  type-code="comparison_rule"
                  :clearable="false"
                  :check-default="false"
                  :only-show-option="['1', '9', '10']"
                  placeholder="请选择对照规则"
                />
              </template>
              <template v-slot:filter-comparison>
                <el-button :disabled="!canComparison" @click="comparison"
                  >自动对照</el-button
                >
              </template>
            </page-filter>
            <div class="flex_full_item">
              <el-form ref="tableForm" :model="tableInfo" style="width: 100%">
                <!-- 表格 -->
                <page-table
                  :refresh="tableInfo.refresh"
                  :init-curpage="tableInfo.initCurpage"
                  v-model:data="tableInfo.data"
                  :pager="false"
                  :tab-index="true"
                  :field-list="tableInfo.fieldList"
                  :handle="tableInfo.handle"
                  :isDynamic="true"
                  @handleEvent="handleEvent"
                >
                  <template v-slot:col-tsProductCode="scope">
                    <el-form-item
                      style="width: 100%; margintop: 18px"
                      :prop="`data.${scope.$index}.tsProductCode`"
                      :rules="
                        scope.$index >= 0
                          ? [
                              {
                                required: true,
                                message: '请选择对方编码',
                                trigger: 'change',
                              },
                            ]
                          : []
                      "
                    >
                      <el-input
                        v-model="scope.row.tsProductCode"
                        style="width: 100%"
                        class="not-mongolia"
                        type="input"
                        :required="true"
                        :disabled="true"
                        :placeholder="'请选择对方编码'"
                      >
                        <template #append>
                          <el-icon @click="checkTsName(scope.$index)"
                            ><MoreFilled
                          /></el-icon>
                        </template>
                      </el-input>
                    </el-form-item>
                  </template>
                </page-table>
              </el-form>
            </div>
          </div>
        </div>
      </full-screen>
    </div>
    <select-ts-product
      v-if="productInfo.visible"
      v-model:show-dialog="productInfo.visible"
      :field-list="productInfo.fieldList"
      :filter-info-list="productInfo.filterInfoList"
      :query="productInfo.query"
      :api="selectProductList"
      :save-empty="false"
      :check-box="true"
      :highlight-row="false"
      @callback="callBackProduct"
    />
    <select-ts-product
      v-if="tsProductInfo.visible"
      v-model:show-dialog="tsProductInfo.visible"
      :query="tsProductInfo.query"
      :api="tsProductInfo.api"
      :save-empty="true"
      :check-box="false"
      :highlight-row="true"
      @callback="callBackTsProduct"
    />
    <page-dialog
      v-show="dialogInfo.visible"
      :title="dialogInfo.title"
      v-model:visible="dialogInfo.visible"
      :width="dialogInfo.width"
      :bt-loading="dialogInfo.btLoading"
      :bt-list="dialogInfo.btList"
      @reset="tsFormInfo.data = {}"
    >
      <page-form
        class="paddingBox order-model-formBox flex_wrap_start_start"
        v-model:ref-obj="tsFormInfo.ref"
        :data="tsFormInfo.data"
        :field-list="tsFormInfo.fieldList"
        :label-width="tsFormInfo.labelWidth"
        :rules="tsFormInfo.rules"
      ></page-form>
    </page-dialog>
  </div>
</template>

<script setup name="comparProductModify">
import {
  mappingTripartiteProductBatchInsert,
  mappingTripartiteProductComparison,
  saveTripartiteSystemProduct,
  getComparisonInfo,
  selectTripartiteProductList,
  selectProductList,
} from '@/api/tripartite'
import SelectTsProduct from '@/views/informationSyncCompar/components/SelectTsProduct/index'

const { proxy } = getCurrentInstance()
const emit = defineEmits()
const props = defineProps(['visible', 'orderId', 'title'])

const formRefs = ref('')
const formInfo = ref({
  ref: null,
  options: [],
  data: {
    tsSystemCode: 'SLIP',
  },
  fieldList: [
    {
      label: '对方系统',
      value: 'tsSystemCode',
      type: 'slot',
    },
  ],
  rules: {},
  labelWidth: '160px',
})
const fullInfo = ref({
  btnList: [{ label: '保存', event: save, show: true }],
})
const filterInfo = ref({
  query: {
    comparisonRule: '1',
  },
  list: [
    { type: 'slot', value: 'add' },
    { type: 'slot', value: 'remove' },
    { type: 'slot', value: 'comparisonRule' },
    { type: 'slot', value: 'comparison' },
  ],
})
// 表格相关
const tableInfo = ref({
  data: [],
  selections: [],
  fieldList: [
    { label: '系统编码', value: 'code' },
    { label: '系统名称', value: 'commonName' },
    { label: '系统型号', value: 'standard' },
    { label: '系统厂家', value: 'brandName' },
    { label: '系统单位', value: 'unitName' },
    {
      label: '系统单位比例',
      value: 'unitScale',
      type: 'number',
      min: 0,
      max: 99999999,
      precision: 4,
      rules: [
        {
          required: true,
          message: '请输入系统单位比例',
          trigger: ['blur', 'change'],
        },
      ],
    },
    { label: '系统挂网产品类型', value: 'networkProductTypeValue' },
    { label: '系统商品代码', value: 'serialNum' },
    { label: '系统商品ID', value: 'procureCatalogId' },
    { label: '对方系统', value: 'tsSystemCode' },
    { label: '对方编码', value: 'tsProductCode', type: 'slot' },
    { label: '对方名称', value: 'tsCommonName' },
    { label: '对方型号', value: 'tsStandard' },
    { label: '对方厂家', value: 'tsBrandName' },
    { label: '对方单位', value: 'tsUnitName' },
    {
      label: '对方单位比例',
      value: 'tsUnitScale',
      type: 'number',
      min: 0,
      max: 99999999,
      precision: 4,
      rules: [
        {
          required: true,
          message: '请输入对方单位比例',
          trigger: ['blur', 'change'],
        },
      ],
    },
  ],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '150',
    btList: [
      {
        label: '新增对方信息',
        event: addTsProduct,
        show: true,
      },
      {
        label: '删除',
        event: remove,
        popconfirmText: '删除后将改变数据,是否继续？',
        show: true,
      },
    ],
  },
})
const productInfo = ref({
  visible: false,
  query: {
    tsSystemCode: '',
    orgId: proxy.$store.state.user.userInfo.user.orgId,
  },
  fieldList: [
    { label: '系统编码', value: 'code' },
    { label: '系统名称', value: 'commonName' },
    { label: '系统型号', value: 'standard' },
    { label: '系统厂家', value: 'brandName' },
    { label: '系统单位', value: 'unitName' },
    { label: '系统挂网产品类型', value: 'networkProductTypeValue' },
    { label: '系统商品代码', value: 'serialNum' },
    { label: '系统商品ID', value: 'procureCatalogId' },
  ],
  filterInfoList: [
    {
      componentType: 'input',
      hidden: true,
      show: true,
      label: '名称/编码',
      value: 'keyWord',
    },
    {
      label: '挂网产品类型',
      value: 'networkProductType',
      // event: search,
      componentType: 'select-model',
      code: 'network_product_type',
      show: true,
      hidden: true,
    },
  ],
})
const tsProductInfo = ref({
  visible: false,
  api: selectTripartiteProductList,
  index: 0,
  query: {
    tsSystemCode: '',
    orgId: proxy.$store.state.user.userInfo.user.orgId,
  },
})
const dialogInfo = ref({
  visible: false,
  title: '新增对方信息',
  btLoading: false,
  type: '',
  msg: '',
  index: 0,
  width: '700px',
  flag: true,
  btList: [
    { label: '关闭', event: handleClose, show: true },
    {
      label: '保存',
      type: 'primary',
      event: checkConfirm,
      show: true,
    },
  ],
})
const tsFormInfo = ref({
  ref: null,
  data: {},
  fieldList: [
    {
      label: '对方编码',
      value: 'tsProductCode',
      type: 'input',
    },
    {
      label: '对方名称',
      value: 'tsCommonName',
      type: 'input',
    },
    { label: '对方型号', value: 'tsStandard', type: 'input' },
    { label: '对方厂家', value: 'tsBrandName', type: 'input' },
    { label: '对方单位', value: 'tsUnitName', type: 'input' },
  ],
  rules: {
    tsProductCode: [
      { required: true, message: '请输入对方编码', trigger: 'blur' },
    ],
    tsCommonName: [
      { required: true, message: '请输入对方名称', trigger: 'blur' },
    ],
  },
  labelWidth: '120px',
})

const showDialog = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    emit('update:visible', newValue) // 更新父组件visible
  },
})

const canRemove = computed(() => {
  return tableInfo.value.selections.length
})
const canComparison = computed(() => {
  return tableInfo.value.data.length
})

onMounted(() => {
  proxy.$nextTick(() => {
    formRefs.value = [proxy.$refs['tableForm'], formInfo.value.ref]
  })
})

function checkConfirm() {
  tsFormInfo.value.ref.validate((valid) => {
    if (valid) {
      let params = {
        ...tsFormInfo.value.data,
        tsSystemCode: formInfo.value.data.tsSystemCode,
      }
      saveTripartiteSystemProduct(params).then((res) => {
        if (res && res.success) {
          let data = res.data
          let index = dialogInfo.value.index
          tableInfo.value.data[index]['tsProductCode'] = data.tsProductCode
          tableInfo.value.data[index]['tsCommonName'] = data.tsCommonName
          tableInfo.value.data[index]['tsStandard'] = data.tsStandard
          tableInfo.value.data[index]['tsBrandName'] = data.tsBrandName
          tableInfo.value.data[index]['tsUnitName'] = data.tsUnitName
          tableInfo.value.data[index]['tsUnitScale'] = 1
          tableInfo.value.data[index]['tsSystemCode'] = data.tsSystemCode
          tableInfo.value.data[index]['tsProductId'] = data.id
          handleClose()
        }
      })
    }
  })
}
function addTsProduct(row, index) {
  dialogInfo.value.index = index
  dialogInfo.value.visible = true
}
function handleClose() {
  dialogInfo.value.visible = false
  tsFormInfo.value.data = {}
}

function changeCode() {
  tableInfo.value.data = []
}
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.value.selections = data
      break
  }
}
function add() {
  productInfo.value.query.idNotIn = tableInfo.value.data.map(
    (item) => item.productId
  )
  productInfo.value.query.tsSystemCode = formInfo.value.data.tsSystemCode
  productInfo.value.visible = true
}
function checkTsName(index) {
  tsProductInfo.value.visible = true
  tsProductInfo.value.index = index
  let ids = []
  tableInfo.value.data.forEach((item) => {
    if (item.tsProductId) {
      ids.push(item.tsProductId)
    }
  })
  tsProductInfo.value.query.idNotIn = ids
  tsProductInfo.value.query.tsSystemCode = formInfo.value.data.tsSystemCode
}
function callBackProduct(data) {
  if (data && data.length) {
    data.forEach((item) => {
      item.productId = item.id
      item.unitScale = 1
      if(formInfo.value.data.tsSystemCode === 'HIS') {
        // 对照HIS系统，对方单位比例默认1
        item.tsUnitScale = 1
      }
    })
    tableInfo.value.data = data.concat(tableInfo.value.data)
  }
}
function callBackTsProduct(data) {
  let index = tsProductInfo.value.index
  if (data && data.id) {
    tableInfo.value.data[index]['tsProductCode'] = data.tsProductCode
    tableInfo.value.data[index]['tsCommonName'] = data.tsCommonName
    tableInfo.value.data[index]['tsStandard'] = data.tsStandard
    tableInfo.value.data[index]['tsBrandName'] = data.tsBrandName
    tableInfo.value.data[index]['tsUnitName'] = data.tsUnitName
    tableInfo.value.data[index]['tsUnitScale'] = 1
    tableInfo.value.data[index]['tsSystemCode'] =
      formInfo.value.data.tsSystemCode
    tableInfo.value.data[index]['tsProductId'] = data.id
  } else {
    tableInfo.value.data[index]['tsProductCode'] = ''
    tableInfo.value.data[index]['tsCommonName'] = ''
    tableInfo.value.data[index]['tsStandard'] = ''
    tableInfo.value.data[index]['tsBrandName'] = ''
    tableInfo.value.data[index]['tsUnitName'] = ''
    tableInfo.value.data[index]['tsUnitScale'] = ''
    tableInfo.value.data[index]['tsSystemCode'] = ''
    tableInfo.value.data[index]['tsProductId'] = ''
  }
}
function remove(row = undefined) {
  if (row && row.code) {
    tableInfo.value.data = tableInfo.value.data.filter((item) => item !== row)
  } else {
    proxy
      .$confirm('删除后将改变数据,是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
      .then(() => {
        tableInfo.value.data = tableInfo.value.data.filter(
          (row) => !tableInfo.value.selections.includes(row)
        )
      })
  }
}
function comparison() {
  let params = {
    ruleCode: filterInfo.value.query.comparisonRule,
    sourceDataList: tableInfo.value.data,
    systemCode: formInfo.value.data.tsSystemCode,
  }
  mappingTripartiteProductComparison(params).then((res) => {
    if (res && res.success) {
      tableInfo.value.data = res.data
    }
  })
}
function save() {
  proxy.$fn
    .checkForm(formRefs.value)
    .then(() => {
      if (!tableInfo.value.data.length) {
        proxy.$message({
          message: '请添加对照产品',
          type: 'warning',
          duration: 3500,
          showClose: true,
        })
        return
      }
      let params = tableInfo.value.data
      mappingTripartiteProductBatchInsert(params).then((res) => {
        if (res && res.success) {
          showDialog.value = false
          emit('returnModify', false)
        }
      })
    })
    .catch(() => {
      proxy.$message({
        message: '必填或非法校验未通过，请检查！',
        type: 'warning',
        duration: 3500,
        showClose: true,
      })
    })
}
</script>

<style scoped lang="scss">
.flex {
  display: flex;
  flex: 1;
}
.flex-select :deep(.el-input--small .el-input__inner) {
  height: 28px !important;
}
:deep(.patrolPlan-checkbox) {
  padding: 0 5px 5px 5px;
  box-sizing: border-box;
  .el-checkbox-button__inner {
    width: 30px;
    height: 30px;
    padding: 0;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
:deep(.el-checkbox-button__inner) {
  border: 1px solid #dcdfe6 !important;
}
</style>
